import yinghua from '../img/yinghua.png'
var stop
var img = new Image()
img.src = yinghua
class Sakura {
  constructor() {
    this.x = this.getRandom('x')
    this.y = this.getRandom('y')
    this.s = this.getRandom('s')
    this.r = this.getRandom('r')
  }
  draw(cxt) {
    cxt.save()
    cxt.translate(this.x, this.y)
    cxt.rotate(this.r)
    cxt.drawImage(img, 0, 0, 40 * this.s, 40 * this.s)
    cxt.restore()
  }
  update() {
    let random

    random = -0.5 + Math.random() * 1
    this.x = this.x + 0.5 * random - 1.7

    random = 1.5 + Math.random() * 0.7
    this.y = this.y + random

    random = Math.random() * 0.03
    this.r = this.r + random

    if (this.x > window.innerWidth || this.x < 0 || this.y > window.innerHeight || this.y < 0) {
      if (Math.random() > 0.4) {
        this.x = this.getRandom('x')
        this.y = 0
      } else {
        this.x = window.innerWidth
        this.y = this.getRandom('y')
      }
      this.s = this.getRandom('s')
      this.r = this.getRandom('r')
    }
  }
  getRandom(option) {
    if (option === 'x') {
      return Math.random() * window.innerWidth
    }
    if (option === 'y') {
      return Math.random() * window.innerHeight
    }
    if (option === 's') {
      return Math.random()
    }
    if (option === 'r') {
      return Math.random() * 6
    }
  }
}

class SakuraList {
  constructor() {
    this.list = []
  }
  push(sakura) {
    this.list.push(sakura)
  }
  update() {
    for (var i = 0, len = this.list.length; i < len; i++) {
      this.list[i].update()
    }
  }
  draw(cxt) {
    for (var i = 0, len = this.list.length; i < len; i++) {
      this.list[i].draw(cxt)
    }
  }
}

let canvas
export function startPlay() {
  canvas = document.createElement('canvas')
  canvas.height = window.innerHeight
  canvas.width = window.innerWidth
  canvas.setAttribute('style', 'position: fixed;left: 0;top: 0;pointer-events: none;')
  document.getElementsByTagName('body')[0].appendChild(canvas)
  let cxt = canvas.getContext('2d')
  var sakuraList = new SakuraList()
  for (var i = 0; i < 50; i++) {
    let sakura = new Sakura()
    sakuraList.push(sakura)
  }

  function play() {
    cxt.clearRect(0, 0, canvas.width, canvas.height)
    sakuraList.update()
    sakuraList.draw(cxt)
    stop = window.requestAnimationFrame(play)
  }
  play()
}
export function stopPlay() {
  if (canvas) {
    canvas.parentNode.removeChild(canvas)
    canvas = null
    window.cancelAnimationFrame(stop)
  }
}
